package com.bookstore.servlet;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/user.do")
public class AdminServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User login = userService.login(new User(username, password));
        //判断是否登录成功
        if (login == null) {
            //登录失败
            resp.sendRedirect(req.getContextPath() + "/admin/login.html");
        } else {
            //登录成功
            //1.往Session当中 保存用户信息
            req.getSession().setAttribute("user", login);
            //2.跳转到主界面
            resp.sendRedirect(req.getContextPath() + "/admin/index.jsp");
        }
    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.销毁Session对象
        req.getSession().invalidate();
        //2.重定向回登录页面
        resp.sendRedirect(req.getContextPath() + "/admin/login.html");
    }
}
